<?php
namespace App\Models;

use App\Config\Database;
use PDO;
use PDOException;

/**
 * 好友关系模型
 * @package App\Models
 * @description:
 * 1. 添加好友
 * 2. 删除好友
 * 3. 获取好友列表
 * 4. 检查好友关系
 */
class Friend {
    private $conn;
    private $table = 'friendships';

    public function __construct() {
        $database = new Database();
        $this->conn = $database->getConnection();
    }

    /**
     * 添加好友关系（双向）
     * @param int $userId 用户ID
     * @param int $friendId 好友ID
     * @return bool
     */
    public function addFriend($userId, $friendId) {
        try {
            $this->conn->beginTransaction();
            
            // 添加正向关系
            $query1 = "INSERT INTO " . $this->table . " 
                      (user_id, friend_id, status) 
                      VALUES (:user_id, :friend_id, 1)";
            $stmt1 = $this->conn->prepare($query1);
            $stmt1->bindParam(':user_id', $userId);
            $stmt1->bindParam(':friend_id', $friendId);
            $stmt1->execute();
            
            // 添加反向关系
            $query2 = "INSERT INTO " . $this->table . " 
                      (user_id, friend_id, status) 
                      VALUES (:user_id, :friend_id, 1)";
            $stmt2 = $this->conn->prepare($query2);
            $stmt2->bindParam(':user_id', $friendId);
            $stmt2->bindParam(':friend_id', $userId);
            $stmt2->execute();
            
            $this->conn->commit();
            return true;
        } catch (PDOException $e) {
            $this->conn->rollBack();
            // 唯一键冲突表示已存在
            if ($e->getCode() == 23000) {
                return true; // 已存在，视为成功
            }
            error_log("Add friend error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * 删除好友关系（双向）
     * @param int $userId 用户ID
     * @param int $friendId 好友ID
     * @return bool
     */
    public function removeFriend($userId, $friendId) {
        try {
            $this->conn->beginTransaction();
            
            // 删除正向关系
            $query1 = "UPDATE " . $this->table . " 
                      SET status = 0 
                      WHERE user_id = :user_id AND friend_id = :friend_id";
            $stmt1 = $this->conn->prepare($query1);
            $stmt1->bindParam(':user_id', $userId);
            $stmt1->bindParam(':friend_id', $friendId);
            $stmt1->execute();
            
            // 删除反向关系
            $query2 = "UPDATE " . $this->table . " 
                      SET status = 0 
                      WHERE user_id = :user_id AND friend_id = :friend_id";
            $stmt2 = $this->conn->prepare($query2);
            $stmt2->bindParam(':user_id', $friendId);
            $stmt2->bindParam(':friend_id', $userId);
            $stmt2->execute();
            
            $this->conn->commit();
            return true;
        } catch (PDOException $e) {
            $this->conn->rollBack();
            error_log("Remove friend error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * 获取好友列表
     * @param int $userId 用户ID
     * @param int $page 页码
     * @param int $pageSize 每页数量
     * @return array
     */
    public function getFriends($userId, $page = 1, $pageSize = 20) {
        try {
            $offset = ($page - 1) * $pageSize;
            
            $query = "SELECT u.id, u.email, u.phone, u.username, u.user_id, u.avatar_url as avatar
                      FROM " . $this->table . " f
                      JOIN users u ON f.friend_id = u.id
                      WHERE f.user_id = :user_id AND f.status = 1
                      ORDER BY f.created_at DESC
                      LIMIT :offset, :limit";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':user_id', $userId);
            $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
            $stmt->bindParam(':limit', $pageSize, PDO::PARAM_INT);
            
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Get friends error: " . $e->getMessage());
            return [];
        }
    }

    /**
     * 检查是否是好友关系
     * @param int $userId 用户ID
     * @param int $friendId 好友ID
     * @return bool
     */
    public function isFriend($userId, $friendId) {
        try {
            $query = "SELECT COUNT(*) as count 
                      FROM " . $this->table . " 
                      WHERE user_id = :user_id AND friend_id = :friend_id AND status = 1";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':user_id', $userId);
            $stmt->bindParam(':friend_id', $friendId);
            $stmt->execute();
            
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            return $result['count'] > 0;
        } catch (PDOException $e) {
            error_log("Check friend relationship error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * 获取共同好友
     * @param int $userId 用户ID
     * @param int $otherUserId 另一个用户ID
     * @return array
     */
    public function getMutualFriends($userId, $otherUserId) {
        try {
            $query = "SELECT u.* 
                      FROM " . $this->table . " f1
                      JOIN " . $this->table . " f2 ON f1.friend_id = f2.friend_id
                      JOIN users u ON f1.friend_id = u.id
                      WHERE f1.user_id = :user_id 
                      AND f2.user_id = :other_user_id
                      AND f1.status = 1 AND f2.status = 1";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':user_id', $userId);
            $stmt->bindParam(':other_user_id', $otherUserId);
            $stmt->execute();
            
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Get mutual friends error: " . $e->getMessage());
            return [];
        }
    }
}